package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer websocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        //处理异常数据 地址为空 购物车为空
        AddressBook addressBook = addressBookMapper.getAddressBookById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        checkOutOfRange(addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail());

        Long userId = BaseContext.getCurrentId();

        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //向订单表中插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);

        orderMapper.insert(orders);

        //向订单明细表中插入多条数据
        List<OrderDetail> orderDetails = new ArrayList<>();

        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());//设置订单id
            orderDetails.add(orderDetail);
        }

        //批量插入订单明细数据
        orderDetailMapper.insertBatch(orderDetails);

        //清空购物车
        shoppingCartMapper.deleteByUserId(userId);

        //封装VO对象
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber()).build();

        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        String OrderNumber = ordersPaymentDTO.getOrderNumber();
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;//订单状态 待接单
        Integer OrderPaidStatus = Orders.PAID;//支付状态 已支付
        LocalDateTime check_out_time = LocalDateTime.now();//支付时间

        orderMapper.updateOrderStatus(OrderNumber, OrderStatus, OrderPaidStatus, check_out_time);

        // 通过websocket向客户端浏览器推送消息 type orderId content
        Orders orders = orderMapper.getByNumber(OrderNumber);

        Map map = new HashMap();
        map.put("type",1); //1表示来单消息 2表示催单消息
        map.put("orderId",orders.getId());
        map.put("content","订单号:" + OrderNumber);

        String json = JSON.toJSONString(map);
        websocketServer.sendToAllClient(json);


        return vo;
    }

    /**
     * 支付成功，修改订单状态
     * 向前端推送来单消息
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    }


    /**
     * 订单分页查询
     *
     * @param orderPageQueryDTO
     * @return
     */
    @Override
    public PageResult orderList(OrdersPageQueryDTO orderPageQueryDTO) {
        PageHelper.startPage(orderPageQueryDTO.getPage(), orderPageQueryDTO.getPageSize());
        //先查订单信息
        Page<Orders> page = orderMapper.pageQuery(orderPageQueryDTO);

        //再查订单的详细信息
        List<OrderVO> listVO = getOrderVOList(page);

        return new PageResult(page.getTotal(), listVO);
    }


    /**
     * 订单统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }


    /**
     * 订单详情查询
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        //订单信息
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);

        //地址信息
        String address = getAddressByIdStr(orders.getAddressBookId());
        orderVO.setAddress(address);

        //菜品信息
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }


    /**
     * 确认订单
     *
     * @param orderConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO orderConfirmDTO) {
        Orders orders = new Orders();
        orders.setId(orderConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }


    /**
     * 配送订单
     * @param id
     */
    @Override
    public void deliverOrder(Long id) {
        //只有待配送的订单才能配送
        Orders ordersDB = orderMapper.getById(id);

        if (ordersDB==null || !(ordersDB.getStatus() == Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS).build();
        orderMapper.update(orders);
    }


    /**
     * 完成订单
     * @param id
     */
    @Override
    public void completeOrder(Long id) {
        //只有派送中的订单才能完成
        Orders ordersDB = orderMapper.getById(id);

        if (ordersDB==null || !(ordersDB.getStatus() == Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }


        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .deliveryTime(LocalDateTime.now()).build();
        orderMapper.update(orders);
    }


    /**
     * 取消订单
     * @param orderCancelDTO
     */
    @Override
    public void cancelOrder(OrdersCancelDTO orderCancelDTO) {
        //获取当前订单
        Orders ordersDB = orderMapper.getById(orderCancelDTO.getId());

        Orders orders = new Orders();
        //如果已付款则需要退款
        if (ordersDB.getPayStatus() == Orders.PAID) {
            try {
                System.out.println("退款" + ordersDB.getAmount() + "元...");
                orders.setPayStatus(Orders.REFUND);
            } catch (Exception e) {
                throw new OrderBusinessException(MessageConstant.UNKNOWN_ERROR);
            }
        }

        orders.setId(orderCancelDTO.getId());

        orders.setStatus(Orders.CANCELLED);

        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(orderCancelDTO.getCancelReason());

        orderMapper.update(orders);
    }


    /**
     * 拒接订单
     * @param orderRejectionDTO
     */
    @Override
    public void rejectOrder(OrdersRejectionDTO orderRejectionDTO) {
        Orders ordersDB = orderMapper.getById(orderRejectionDTO.getId());

        //只有待接单的订单才能拒单
        if (ordersDB==null || !(ordersDB.getStatus() == Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();

        if (ordersDB.getPayStatus() == Orders.PAID) {
            //如果已付款，需要退款
            try {
                System.out.println("退款" + ordersDB.getAmount() + "元...");
            } catch (Exception e) {
                throw new OrderBusinessException(MessageConstant.UNKNOWN_ERROR);
            }
        }

        orders.setId(orderRejectionDTO.getId());

        orders.setStatus(Orders.CANCELLED);

        orders.setRejectionReason(orderRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());


        orderMapper.update(orders);
    }


    /**
     * 历史订单
     * @param pageNumber
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult historyOrder(Integer pageNumber, Integer pageSize, Integer status) {
        PageHelper.startPage(pageNumber,pageSize);
        OrdersPageQueryDTO orderPageQueryDTO = new OrdersPageQueryDTO();
        orderPageQueryDTO.setStatus(status);
        orderPageQueryDTO.setUserId(BaseContext.getCurrentId());

        Page<Orders> page = orderMapper.pageQuery(orderPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        //封装VO
        if(page!=null && page.getTotal() >0){
            for (Orders orders : page) {
                Long id = orders.getId();

                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders,orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(),list);
    }


    /**
     * 用户取消订单
     * @param id
     */
    @Override
    public void userCancelOrder(Long id) {
        //获取当前订单
        Orders orderDB = orderMapper.getById(id);

        if(orderDB == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if(orderDB.getStatus() > Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(orderDB.getId());

        //如果已付款，需要退款
        if(Objects.equals(orderDB.getStatus(), Orders.TO_BE_CONFIRMED)){
            System.out.println("用户退款" + orderDB.getAmount() + "元...");
            orders.setPayStatus(Orders.REFUND);
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason("用户取消");
        orderMapper.update(orders);

    }


    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        Long userId  = BaseContext.getCurrentId();
        //获取当前订单详细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        if(orderDetailList == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //将订单详细对象转化为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            //设置购物车对象相关属性
            BeanUtils.copyProperties(x,shoppingCart,"id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        shoppingCartMapper.insertBatch(shoppingCartList);
    }


    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //查询订单
        Orders orders = orderMapper.getById(id);
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //发送短信
        Map map = new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号：" + orders.getNumber());

        String json = JSON.toJSONString(map);
        websocketServer.sendToAllClient(json);
    }


    /**
     * 封装订单VO
     * @param page
     * @return
     */
    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        List<OrderVO> list = new ArrayList<>();

        List<Orders> ordersList = page.getResult();

        if (!ordersList.isEmpty()) {
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                String address = getAddressByIdStr(orders.getAddressBookId());
                orderVO.setAddress(address);
                String orderDishes = getOrderDishesStr(orders);

                //封装菜品信息
                orderVO.setOrderDishes(orderDishes);
                list.add(orderVO);
            }
        }
        return list;
    }


    /**
     * 根据地址id查询地址信息
     *
     * @param addressBookId
     * @return
     */
    private String getAddressByIdStr(Long addressBookId) {
        AddressBook addressBook = addressBookMapper.getAddressBookById(addressBookId);
        return addressBook.getProvinceName() + addressBook.getCityName()
                + addressBook.getDistrictName() + addressBook.getDetail();
    }

    /**
     * 封装菜品信息
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        List<OrderDetail> list = orderDetailMapper.getByOrderId(orders.getId());

        //拼接菜品信息
        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = list.stream().map(x -> {
            return x.getName() + "*" + x.getNumber() + ";";
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);

    }


    /**
     * 检查地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address){
        //获取商家的地址
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        String shopCoordinate = HttpClientUtil.doGet("http://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;


        //获取用户地址的经纬度坐标
        map.put("address",address);
        String userCoordinate = HttpClientUtil.doGet("http://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;


        //路线规划
        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

}
